/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.motion.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.cooperation.entity.BizCooperation;
import vip.xiaonuo.biz.modular.file.provider.BizFileApiProvider;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.motion.entity.BizMotion;
import vip.xiaonuo.biz.modular.motion.mapper.BizMotionMapper;
import vip.xiaonuo.biz.modular.motion.param.BizMotionAddParam;
import vip.xiaonuo.biz.modular.motion.param.BizMotionEditParam;
import vip.xiaonuo.biz.modular.motion.param.BizMotionIdParam;
import vip.xiaonuo.biz.modular.motion.param.BizMotionPageParam;
import vip.xiaonuo.biz.modular.motion.service.BizMotionService;
import vip.xiaonuo.sys.api.SysUserApi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 职工议案Service接口实现类
 *
 * @author xsl
 * @date  2024/08/13 16:22
 **/
@Service
public class BizMotionServiceImpl extends ServiceImpl<BizMotionMapper, BizMotion> implements BizMotionService {

    @Resource
    BizFileApiProvider bizFileApiProvider;

    @Resource
    SysUserApi sysUserApi;

    @Override
    public Page<BizMotion> page(BizMotionPageParam bizMotionPageParam) {
        QueryWrapper<BizMotion> queryWrapper = new QueryWrapper<BizMotion>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizMotionPageParam.getCongressId())) {
            queryWrapper.lambda().like(BizMotion::getCongressId, bizMotionPageParam.getCongressId());
        }
        if(ObjectUtil.isNotEmpty(bizMotionPageParam.getOrgId())) {
            queryWrapper.lambda().like(BizMotion::getOrgId, bizMotionPageParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(bizMotionPageParam.getMotionFileId())) {
            queryWrapper.lambda().like(BizMotion::getMotionFileId, bizMotionPageParam.getMotionFileId());
        }
        if(ObjectUtil.isAllNotEmpty(bizMotionPageParam.getSortField(), bizMotionPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizMotionPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizMotionPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizMotionPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizMotion::getId);
        }

        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.lambda().in(BizMotion::getOrgId, loginUserDataScope);
        } else {
            queryWrapper.lambda().eq(BizMotion::getCreateUser, StpUtil.getLoginIdAsString());
        }

        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizMotionAddParam bizMotionAddParam) {
        List<String> fileList = bizMotionAddParam.getFileList();
        for(String item : fileList){
            BizMotion bizMotion = new BizMotion();
            bizMotion.setMotionFileId(item);
            bizMotion.setCongressId(bizMotionAddParam.getCongressId());
            bizMotion.setCongressName(bizMotionAddParam.getCongressName());
            this.save(bizMotion);
            JSONObject sysOrg = sysUserApi.getUserOrg(bizMotion.getCreateUser());
            JSONObject sysUser = sysUserApi.getUserByIdWithoutException(bizMotion.getCreateUser());
            // 将JSONObject转换成Map
            Map orgMap = sysOrg.toBean(Map.class);
            Map userMap = sysUser.toBean(Map.class);
            bizMotion.setOrgId((String) orgMap.get("id"));
            bizMotion.setOrgName((String) orgMap.get("name"));
            bizMotion.setCreateUserName((String) userMap.get("name"));
            this.updateById(bizMotion);
            bizFileApiProvider.updateFile(item,bizMotionAddParam.getCongressId(),bizMotion.getId(),"议案文件");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizMotionEditParam bizMotionEditParam) {
        BizMotion bizMotion = this.queryEntity(bizMotionEditParam.getId());
        BeanUtil.copyProperties(bizMotionEditParam, bizMotion);
        this.updateById(bizMotion);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizMotionIdParam> bizMotionIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizMotionIdParamList, BizMotionIdParam::getId));
    }

    @Override
    public BizMotion detail(BizMotionIdParam bizMotionIdParam) {
        return this.queryEntity(bizMotionIdParam.getId());
    }

    @Override
    public BizMotion queryEntity(String id) {
        BizMotion bizMotion = this.getById(id);
        if(ObjectUtil.isEmpty(bizMotion)) {
            throw new CommonException("职工议案不存在，id值为：{}", id);
        }
        return bizMotion;
    }
}
